package sqls

import (
	"database/sql"
	_ "github.com/go-sql-driver/mysql"
	"EasyReson/global"
	"fmt"
	log "code.google.com/p/log4go"
)

/**
	获取一个新的数据库
 */
func NewDb(task *global.Task,userName string,passWord string,ip string,port string,database string,character string,maxOpenConns int,maxIdleConns int) *sql.DB{
	connectStr := getConnectUrl(task.TaskId,task.TaskName,userName,passWord,ip,port,database,character)
	db,err := sql.Open("mysql",connectStr)
	db.SetMaxOpenConns(maxOpenConns)
	db.SetMaxIdleConns(maxIdleConns)
	global.PanicError(err,task)
	db.Ping()
	global.PanicError(err,task)
	return db
}

/**
	根据配置解析连接地址
 */
func getConnectUrl(taskId string,taskName string,userName string,passWord string,ip string,port string,database string,character string) string {

	connect := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s",
		userName,passWord,ip,port,database,character)

	log.Info("taskId [%s] taskName [%s] mysql connection url : [%s]",taskId,taskName,connect)
	return connect
}

